#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
微信客服会话状态问题诊断脚本
"""

import os
import sys
import logging
from dotenv import load_dotenv

sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from config.settings import settings
from services.wx_api import WeChatAPI

logging.basicConfig(level=logging.INFO)

def analyze_log_issue():
    """分析日志中的问题"""
    print("🔍 问题分析:")
    print("1. AI回复已生成但发送失败")
    print("2. 会话状态为0（未接待）")
    print("3. 需要先建立会话才能发送消息")

def test_session_establishment():
    """测试会话建立功能"""
    print("\n🧪 测试会话建立...")
    
    load_dotenv()
    os.environ['WX_CORPID'] = settings.WX_CORPID
    os.environ['WX_CORPSECRET'] = settings.WX_CORPSECRET
    
    wx_api = WeChatAPI()
    access_token = wx_api.get_access_token()
    
    if not access_token:
        print("❌ 无法获取access_token")
        return
    
    open_kfid = settings.OPEN_KF_ID
    external_userid = "wmtI2SEAAAvOQbOUmj28OCNdTYqYIaYw"
    
    # 检查当前会话状态
    session_status = wx_api.check_session_status(open_kfid, external_userid, access_token)
    
    if session_status and session_status.get('errcode') == 0:
        service_state = session_status.get('service_state', 0)
        print(f"当前会话状态: {service_state}")
        
        if service_state == 0:
            print("⚠️ 会话未建立，需要先建立会话")

def main():
    print("🚀 微信客服会话状态问题诊断")
    analyze_log_issue()
    test_session_establishment()
    print("\n🛠️ 解决方案: 在发送消息前先建立会话")

if __name__ == '__main__':
    main() 